package com.jspxcms.common.util;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 */
public class JsonResponse {
    public static Object jsonOutput(HttpServletResponse response, int code, String message, Object val) {
        response.setHeader("Content-type", "application/json");
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("{");
            builder.append("\"code\":").append(code);
            if (message != null) {
                builder.append(",\"message\":\"").append(message.replace("\"", "")).append("\"");
            }
            if (val != null) {
                builder.append(",\"val\":").append(new JsonMapper().toJson(val));
            }
            builder.append("}");
            response.getWriter().append(builder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object jsonOutput(HttpServletResponse response, int code, String message) {
        return jsonOutput(response, code, message, null);
    }
}
